package com.tl.ip_location_relation_v4.service;

import java.util.List;

import com.tl.ip_location_relation_v4.entity.Ip;
import com.tl.ip_location_relation_v4.utils.IpUtil;

public class IpSearchV1 {
	/**
	 * 
	 * @author Antg
	 * @date 2021年7月6日
	 * @param 
	 * @retun
	 * @Description 普通方法查询
	 */
	public static int searchIpLocation(List<Ip> list,String ip){
		long searchIp = IpUtil.ipToLong(ip);
		for(int i = 0;i<list.size();i++){
			Ip temp = list.get(i);
			if(searchIp>=temp.getStartIp()&&searchIp<=temp.getEndIp()){
				return i;
			}
		}
		return -1;
	}
	/**
	 * 
	 * @author Antg
	 * @date 2021年7月6日
	 * @param 
	 * @retun 小于0未查询失败,大于0返回下标
	 * @Description 二分查找(while循环实现)
	 */
	public static int biSearchByLoop(List<Ip> ipList,String searchIp){
		long key = IpUtil.ipToLong(searchIp);
		int low = 0;
		int height = ipList.size()-1;
		int middle = 0;
		while(low<=height){
			middle = (low+height)/2;
			//首先判断是否查询到了
			if(key>=ipList.get(middle).getStartIp()&&key<=ipList.get(middle).getEndIp()){
				return middle;
			}
			//没有查询到就移动位置
			if(ipList.get(middle).getEndIp()>key){//大于最大就查询
				height = middle-1;
			}else{
				low = middle+1;
			}
		}
		return -1;
	}
	/**
	 * 
	 * @author Antg
	 * @date 2021年7月6日
	 * @param 
	 * @retun
	 * @Description 二分查找(递归实现)
	 */
	public static int biSearchByRecursion(List<Ip> ipList,String searchIp,int low,int height){
		//结束条件判断
		if(low>height){
			return -1;
		}
		long ip = IpUtil.ipToLong(searchIp);
		int middle = (low+height)/2;
		Ip midIp = ipList.get(middle);
		if(ip>=midIp.getStartIp()&&ip<=midIp.getEndIp()){
			return middle;
		}
		if(ip>midIp.getEndIp()){
			low = middle+1;
		}else{
			height = middle-1;
		}
		return biSearchByRecursion(ipList, searchIp, low, height);
	}
	
	/**
	 * 
	 * @author Antg
	 * @date 2021年7月6日
	 * @param 
	 * @retun
	 * @Description 对递归二分查找的再次封装
	 */
	public static int biSearchByRecursion(List<Ip> ipList,String searchIp){
		return biSearchByRecursion(ipList, searchIp, 0, ipList.size()-1);
	}
	
}
